<?php


namespace app\service\user;


use app\model\config\CouponModel;
use app\model\user\UserCouponModel;
use app\service\BaseService;

class UserCouponService extends BaseService
{

    public function __construct()
    {
        $this->model = new UserCouponModel();
    }

    /**
     * 订单可用优惠券
     * @param $userId
     * @param $amount
     * @param $type 1学车优惠券 2验车优惠券  3陪驾优惠券
     * @return UserCouponModel[]|array|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getOrderCouponList($userId, $amount, $type)
    {
        $list = $this->model->where('user_id', $userId)
            ->where('is_used', 0)
            ->where('status', 0)
            ->where('use_type', $type)
            ->where('less_amount', '<=', $amount)
            ->select();
        return $list;
    }

    /**
     * 给用户发优惠券
     * @param $userId
     * @param $couponIdArr
     * @throws \Exception
     */
    public function sendCouponToUser($userId, $couponIdArr)
    {
        $dataAll = [];
        foreach ($couponIdArr as $k => $couponId) {
            $couponService = new CouponService();
            $couponInfo = $couponService->getOneLineById($couponId);
            if (!$couponInfo) {
                continue;
            }
            $dataAll[$k] = [
                'user_id' => $userId,
                'coupon_id' => $couponId,
                'coupon_name' => $couponInfo['coupon_name'],
                'amount' => $couponInfo['amount'],
                'use_start_time' => time(),
                'use_end_time' => strtotime($couponInfo['use_end_time']),
                'use_type' => $couponInfo['use_type'],
            ];
        }
        if ($dataAll) {
            $model = clone $this->model;
            $model->saveAll($dataAll);
        }
    }

    /**
     * 批量发券
     * @param $userIdArr
     * @param $couponId
     * @throws \Exception
     */
    public function sendCouponToUserArr($userIdArr, $couponId)
    {
        $dataAll = [];
        foreach ($userIdArr as $k => $uid) {
            $couponService = new CouponService();
            $couponInfo = $couponService->getOneLineById($couponId);
            if (!$couponInfo) {
                continue;
            }
            $dataAll[$k] = [
                'user_id' => $uid,
                'coupon_id' => $couponId,
                'coupon_name' => $couponInfo['coupon_name'],
                'amount' => $couponInfo['amount'],
                'use_start_time' => time(),
                'use_end_time' => strtotime($couponInfo['use_end_time']),
                'use_type' => $couponInfo['use_type'],
            ];
        }
        if ($dataAll) {
            $model = clone $this->model;
            $model->saveAll($dataAll);
        }
    }
}